package com.ss.mq.pattern.pubsub;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.ss.mq.util.RabbitUtils;

import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * Publish & Subscribe Model
 * @author 叁昇
 * @create 2020-12-13-18:43
 */
public class PubSubProducer {
    public static void main(String[] args) throws Exception {
        Connection connection = RabbitUtils.getConnection();
        Channel channel = connection.createChannel();

        // 定义一个名称为 log , 类型为 fanout 的交换机
        channel.exchangeDeclare("fanout_log", BuiltinExchangeType.FANOUT);

        while (true) {
            System.out.print("请输入消息: ");
            String msg = new Scanner(System.in).nextLine();
            if ("exit".equals(msg)) break;

            /*
                第一个参数: 向指定的交换机发送消息
                第二个参数: 如果不指定队列, 则由消费者自己向交换机绑定队列
             */
           channel.basicPublish("fanout_log", "", null, msg.getBytes(StandardCharsets.UTF_8));
           System.out.println("消息已发送: [ "+ msg +" ]");
        }

        channel.close();
    }
}
